//index.js
//获取应用实例
const app = getApp()
const util = require('../../utils/util.js');
const urls = require('../../utils/url.js');
const event = require('../../utils/events.js')
const win = util.getSystemHW();
const today = util.formatTime(new Date());
const showTime = today.split(" ")[0]+' '+today.split(" ")[1];
const tips = [
  {'color':'rgba(68, 231, 237,0.9)','text':'构成我们学习最大障碍的是已知的东西，而不是未知的东西','time':showTime},
  {'color':'rgba(247, 81, 197,0.9)','text':'学习和研究好比爬梯子，要一步一步地往上爬，企图一脚跨上四五步，平地登天，那就必须会摔跤了','time':showTime},
  {'color':'rgba(247, 156, 37,0.9)','text':'只有让学生不把全部时间都用在学习上，而留下许多自由支配的时间，他才能顺利地学习，这是教育过程的逻辑','time':showTime}
];
Page({
  tabArrList:{},
  data: {
    scrollHeight: win.windowHeight-42,
    childWidth:win.windowWidth/2,
    scrollTop:0,
    userInfo: {},
    hasUserInfo: false,
    leftList:[],
    rightList:[],
    nav:[],
    hasMore:false,
    page:1,
    currentTab:0,
    isAuthorized:true,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    tip:tips[Math.round(Math.random()*(tips.length-1))]
  },
  time: 0,
  touchDot: 0,//触摸时的原点
  interval: "",
  navIndex:0,
  flag_hd: true,
  componentObj:{},
  isEnd:false,
  //事件处理函数
  onLoad: function () {

    var thisObj = this;
    if (app.globalData.userInfo) {
      this.userObj = util.getStorageInfo('userInfo');
      this.getIndexData(urls.index+"&auth_key="+this.userObj.auth_key,(res)=>{
        thisObj.setUpData(res,(res.category[0].category_id)+'',this.data.page,true);
      });

    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.userObj = util.getStorageInfo('userInfo');
        this.getIndexData(urls.index+"&auth_key="+this.userObj.auth_key,(res)=>{
          thisObj.setUpData(res,(res.category[0].category_id)+'',this.data.page,true);
          thisObj.navIndex = 0;
        });
      }
      app.userInfoUnauthriodCallback = res =>{
        thisObj.setData({
          isAuthorized:false,
        });
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      app.getwxUserInfo(true);
    };
    event.on('DataChanged', this, function(data) {
      var currentNewList = data.direct==="left"?this.data.leftList:this.data.rightList;
      var tempObj = currentNewList[Number(data.index)];
      tempObj.last_read_content_id = data.contentId;
      tempObj.last_read_mulu_id = data.muluId;
      currentNewList[data.index] = tempObj;
      if(data.direct==="left"){
        thisObj.setData({
          leftList:currentNewList
        });
      }else{
        thisObj.setData({
          rightList:currentNewList
        });
      }

    })
  },
  onUnload: function() {
    event.remove('DataChanged', this);
  },
  onReady: function(){

  },
  __loginEvent: function(e){
    // 获取用户信息
    if(e.detail.errMsg==="getUserInfo:fail auth deny"){
      app.globalData.userInfo = null;
      if (app.userInfoUnauthriodCallback) {
        app.userInfoUnauthriodCallback(res)
      }
    }else{
      app.getwxUserInfo(true);
    }
  },
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }else{
      // 右上角转发菜单
      console.log(res.target)
    };
    return {
      title: '阅米粒',
      path: '/pages/index/index',
      success: function(res) {
        // 转发成功
        console.log(res);
      },
      fail: function(res) {
        // 转发失败
        console.log(res);
      }
    }
  },

  setUpData: function(res,key,page,isInit){
    var leftlist = this.data.leftList;
    var rightlist=this.data.rightList;
    var thisObj = this;
    var curArrObj_f = leftlist.length>rightlist.length?rightlist:leftlist;
    var curArrObj_s = leftlist.length>rightlist.length?leftlist:rightlist;
    for(var i=0;i<res.list.length;i++){
      if(thisObj.page>1){
        if(i%2===0){
          curArrObj_f.push(res.list[i]);
        }else{
          curArrObj_s.push(res.list[i]);
        }
      }else{
        if(i%2>0){
          leftlist.push(res.list[i]);
        }else{
          rightlist.push(res.list[i]);
        }
      }
    };
    this.tabArrList[key] = {l_list:leftlist,r_list:rightlist,page:page};
    if(!isInit){
      thisObj.setData({
        userInfo: res.userInfo,
        hasUserInfo: true,
        leftList:leftlist,
        rightList:rightlist,
        isAuthorized:true,
        page:page,
        hasMore:res.has_more>0?true:false,
        tip:tips[Math.round(Math.random()*(tips.length-1))]
      });
    }else{
      thisObj.setData({
        userInfo: res.userInfo,
        hasUserInfo: true,
        leftList:leftlist,
        rightList:rightlist,
        activeId:key,
        page:page,
        isAuthorized:true,
        nav:res.category,
        hasMore:res.has_more>0?true:false,
      });
    }
  },
  initComponent: function(e){
    this.componentObj[e.detail.componentName] = e.detail.componentObj;
  },
  getIndexData: function(url,callback){
    console.log(url);
    if(util.isVailValue(url)){
      util.get(url,callback);
    }
  },
  switchTagEvent: function(e){
    var thisObj = this;
    var curActiveId = e.detail.activeId;
    var curActiveIndex = e.detail.activeIndex;
    this.navIndex = curActiveIndex;
    this.flag_hd = true;
    if(this.tabArrList[curActiveId]){
      var curpage = this.tabArrList[curActiveId].page;
      this.setData({leftList:this.tabArrList[curActiveId].l_list,rightList:this.tabArrList[curActiveId].r_list,scrollTop:0,page:curpage,currentTab:this.navIndex});
    }else{
      var curpage = 1;
      var curUrl = urls.index+"&auth_key="+this.userObj.auth_key+"&page=1&pagesize=10&category_id="+curActiveId;
      this.getIndexData(curUrl,(res)=>{
        this.setData({leftList:[],rightList:[],scrollTop:0,page:curpage,currentTab:this.navIndex})
        thisObj.setUpData(res,curActiveId,curpage,false);
      });
    }

  },
  getDomSize: function(id,callback,obj){
    util.getSeletorLoction(id,obj&&obj!==undefined&&obj!==null?obj:this,(res)=>{
      if(callback){
        callback(res);
      }
    })
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo;
    var thisObj = this;
    this.getIndexData(urls.index+"&auth_key="+this.userObj.auth_key,(res)=>{
      thisObj.setUpData(res,(res.category[0].category_id)+'',thisObj.data.page,true);
    });
  },
  scroll: function(e){
    // console.log(e.currentTarget);
  },
  lower: function(e){
    var thisObj = this;
    if(!thisObj.isEnd){
      thisObj.isEnd = true;
      var curPage = this.data.page+1;
      var curActiveId = this.data.activeId;
      var curUrl = urls.index+"&auth_key="+this.userObj.auth_key+"&page="+curPage+"&pagesize=10&category_id="+curActiveId;
      this.getIndexData(curUrl,(res)=>{
        thisObj.isEnd = false;
        thisObj.setUpData(res,curActiveId,curPage,false);
      });
    }


  },
  upper: function(e){
    // console.log(e.currentTarget);
  },
  detailEvent: function(e){
    var dataId = '';
    var dataName = '';
    var dataCover='';
    var dataDesc='';
    var autorHead='';
    var autorName='';
    var lastContentId='';
    var lastMuluId='';
    var dataIndex = 0;
    var dataDirect = '';
    if(e.detail&&e.detail.isTigger){
      dataId = e.detail.dataId;
      dataName = e.detail.dataName;
      dataCover = e.detail.dataCover;
      dataDesc = e.detail.dataDesc;
      autorHead = e.detail.autorHead;
      autorName = e.detail.autorName;
      lastContentId = e.detail.dataLastCId;
      lastMuluId = e.detail.dataLastMId;
      dataIndex = e.detail.dataIndex;
      dataDirect = e.detail.dataDirect;
    }else{
      dataId = e.currentTarget.id;
      dataName = e.currentTarget.dataset.postName;
      dataCover = e.currentTarget.dataset.postCover;
      dataDesc = e.currentTarget.dataset.postDesc;
      autorHead = e.currentTarget.dataset.autorHead;
      autorName = e.currentTarget.dataset.autorName;
      lastContentId = e.currentTarget.dataset.postLrcid;
      lastMuluId = e.currentTarget.dataset.postLrmid;
      dataIndex = e.currentTarget.dataset.postIndex;
      dataDirect = e.currentTarget.dataset.postDirect;
    }
    wx.navigateTo({
      url: '../detail/detail?dataId='+dataId+'&dataName='+dataName+
      '&dataCover='+dataCover+'&dataDesc='+dataDesc+'&autorHead='+autorHead+'&autorName='+autorName+
      '&lastContentId='+lastContentId+'&lastMuluId='+lastMuluId+'&dataIndex='+dataIndex+'&dataDirect='+dataDirect
    })
  },
  // 滚动list切换标签
  switchTab:function(e){
    this.setData({
      currentTab:e.detail.current,
      hasMore:true,
      leftList:[],
      rightList:[],
    });
    var curComponentObj = this.componentObj["navbar"];
    this.navIndex = e.detail.current;
    curComponentObj.__tagtouch_event({navIndex:this.navIndex});
  },
  switchListStart: function(e){
    var thisObj = this;
    thisObj.touchDot = e.touches[0].pageX; // 获取触摸时的原点
    // 使用js计时器记录时间
    thisObj.interval = setInterval(function () {
    thisObj.time++;
   }, 100);
  },
  switchListEnd: function(e){
    var thisObj = this;
    var touchMove = e.changedTouches[0].pageX;
    // 向左滑动
    if (touchMove - thisObj.touchDot <= -40 && thisObj.time < 10 && thisObj.flag_hd == true
    &&thisObj.navIndex<thisObj.data.nav.length-1) {
       thisObj.flag_hd = false;
       //执行切换页面的方法
       var curComponentObj = this.componentObj["navbar"];
       ++thisObj.navIndex;
       curComponentObj.__tagtouch_event({navIndex:thisObj.navIndex});
    }
    // 向右滑动
    if (touchMove - thisObj.touchDot >= 40 && thisObj.time < 10 && thisObj.flag_hd == true
      &&thisObj.navIndex>0) {
       thisObj.flag_hd = false;
       //执行切换页面的方法
       var curComponentObj = this.componentObj["navbar"];
       --thisObj.navIndex;
       curComponentObj.__tagtouch_event({navIndex:thisObj.navIndex});
    }
    clearInterval(thisObj.interval); // 清除setInterval
    thisObj.time = 0;
   }
})
